<template>
  <div class="p-6">
    <el-form :model="form" label-width="90px" ref="userForm" class="mb-4">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <el-form-item label="用户名" prop="username" class="label-ellipsis">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname" class="label-ellipsis">
          <el-input v-model="form.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" class="label-ellipsis">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" class="label-ellipsis">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="QQ号码" prop="qq" class="label-ellipsis">
          <el-input v-model="form.qq" placeholder="请输入QQ号码" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard" class="label-ellipsis">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="状态" prop="status" class="label-ellipsis">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="正常" value="normal" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role" class="label-ellipsis">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="用户" value="user" />
          </el-select>
        </el-form-item>
      </div>
      <div class="mt-4 flex space-x-2">
        <el-button type="primary" @click="submitForm">查询用户</el-button>
        <el-button type="success" @click="createUser">创建用户</el-button>
      </div>
    </el-form>

    <h2 class="text-xl font-semibold mb-2">用户列表</h2>
    <el-table :data="users" stripe>
      <el-table-column prop="username" label="用户名" show-overflow-tooltip/>
      <el-table-column prop="realname" label="真实姓名" show-overflow-tooltip/>
      <el-table-column prop="phone" label="联系电话" show-overflow-tooltip/>
      <el-table-column prop="email" label="邮箱" show-overflow-tooltip/>
      <el-table-column prop="status" label="状态" show-overflow-tooltip/>
      <el-table-column prop="role" label="角色" show-overflow-tooltip/>
      <el-table-column fixed="right" label="操作" min-width="150">
        <template #default="scope">
          <el-button @click="editUser(scope.row)" size="small" class="text-blue-500">编辑</el-button>
          <el-button @click="deleteUser(scope.row.id)" size="small" class="text-red-500 ml-2">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination class="mt-4" :current-page.sync="currentPage" :page-size="pageSize" :total="totalUsers"
      @current-change="handlePageChange" layout="total, prev, pager, next, jumper" />
    <el-dialog v-model="dialogVisible" title="表单" width="540">
      <UserForm :user="curUser" @submit="handleUserSubmit" />
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import UserForm from './forms/UserForm.vue';

export default {
  components: {
    UserForm,
  },
  data() {
    return {
      dialogVisible: false,
      curUser: {},
      isEdit: false,
      form: {
        username: '',
        realname: '',
        phone: '',
        email: '',
        qq: '',
        idCard: '',
        status: '',
        role: '',
      },
      users: [],
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    this.getUsers();
  },
  methods: {
    async getUsers() {
      try {
        const response = await axios.get('/api/users', {
          params: {
            ...this.form,
            page: this.currentPage,
            pageSize: this.pageSize,
          },
        });
        this.users = response.data.users; // 假设返回的数据结构为 { users: [], total: 0 }
        this.totalUsers = response.data.total; // 获取总用户数
      } catch (error) {
        console.error('获取用户失败:', error);
      }
    },
    async handleUserSubmit(form) {
      try {
        if (this.isEdit) {
          await axios.patch(`/api/users/${form.id}`, form);
        } else {
          await axios.post('/api/users', form);
        }
        
        this.getUsers();
        this.dialogVisible = false;

      } catch (error) {
        console.error('操作失败:', error);
      }
    },
    async createUser() {
      this.curUser = {};
      this.isEdit = false;
      this.dialogVisible = true;
    },
    async deleteUser(id) {
      try {
        await axios.delete(`/api/users/${id}`);
        this.getUsers(); // 刷新用户列表
      } catch (error) {
        console.error('删除用户失败:', error);
      }
    },
    editUser(user) {
      this.curUser = user;
      this.isEdit = true;
      this.dialogVisible = true;
    },
    resetForm() {
      this.form = {
        username: '',
        realname: '',
        phone: '',
        email: '',
        qq: '',
        idCard: '',
        status: '',
        role: '',
      };
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.getUsers();
    },
    submitForm() {
      this.getUsers();
    }
  },
};
</script>

<style>
.label-ellipsis .el-form-item__label {
  max-width: 90px; /* 根据需要调整最大宽度 */
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>